package com.lst.servlet;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.JPushEnum;
import com.lst.common.JPushMessage;
import com.lst.dao.ClientAccomplishMapper;
import com.lst.dao.MstCodeMapper;
import com.lst.entity.request.CliNumReqPara;
import com.lst.model.ClientAccomplish;
import com.lst.model.ClientGrowth;
import com.lst.model.ClientNum;
import com.lst.model.MstClient;
import com.lst.model.MstCode;
import com.lst.model.MstGrade;
import com.lst.model.MstMessage;
import com.lst.service.ClientGrowthService;
import com.lst.service.ClientNumService;
import com.lst.service.MstClientService;
import com.lst.service.MstGradeService;
import com.lst.service.MstMessageService;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: NumAddServlet
 * @Description::统计量添加接口
 * @author zmm
 * @date 2017年9月29日 上午11:19:11
 * 
 */
public class NumAddServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);

	private ClientGrowthService clientGrowthService = ctx.getBean(ClientGrowthService.class);

	private MstCodeMapper mstCodeMapper = ctx.getBean(MstCodeMapper.class);

	private ClientAccomplishMapper clientAccomplishMapper = ctx.getBean(ClientAccomplishMapper.class);

	private MstGradeService mstGradeService = ctx.getBean(MstGradeService.class);
	
    private MstMessageService mstMessageService = ctx.getBean(MstMessageService.class);
    
    private MstClientService mstClientService = ctx.getBean(MstClientService.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();

		BaseResponse resPara = new BaseResponse();

		try {
			CliNumReqPara reqPara = getReqPara(request);

			if (isCheckField(reqPara, resPara)) {

				Integer actid = Integer.valueOf(reqPara.getActid());
				Integer acttype = Integer.valueOf(reqPara.getActtype());
				Integer numtype = Integer.valueOf(reqPara.getNumtype());
				Integer userid = Integer.valueOf(reqPara.getUserid());
				Integer receiveId =StringUtils.isEmpty(reqPara.getReceiveId()) ? 0:Integer.valueOf(reqPara.getReceiveId());

				Map<String, Object> reqMap = new HashMap<String, Object>();

				reqMap.put("actid", actid);
				reqMap.put("acttype", acttype);
				reqMap.put("numtype", numtype);
				if (!StringUtils.isEmpty(userid)) {
					reqMap.put("clientid", userid);
				}

				// 用户统计
				List<ClientNum> cnlist = clientNumService.queryByList(reqMap);
				ClientNum cn = null;
				if (CommCode.SYSTEM_COUNT_PRAISE.equals(numtype)) {// 点赞35
					if (null == cnlist || cnlist.size() == 0) {

						cn = new ClientNum();
						cn.setActid(actid);
						cn.setActtype(acttype);
						cn.setClientid(userid);
						cn.setCreatedate(startDate);
						cn.setCreateuser(userid);
						cn.setEnabled(true);
						cn.setIsdeleted(false);
						cn.setNum(1);
						cn.setNumtype(numtype);

						clientNumService.insert(cn);			

						resPara.setCode(CommCode.M_Y000000);
						resPara.setMessage(CommCode.M_D000001);
						
						if(Integer.valueOf(userid).intValue()!=receiveId.intValue()){
							//点赞对发送评论者发送通知
							MstClient mstClient2=mstClientService.selectByPrimaryKey(receiveId);
							if(mstClient2!=null){
								if(mstClient2.getThumbStatus()){
									MstClient mstClient=mstClientService.selectByPrimaryKey(userid);
									String name=mstClient.getNickname();
								//	String portrait=mstClient.getPortrait();
									
								      MstMessage message=new MstMessage();
								      message.setReceiveid(receiveId);
								      message.setReceivetype(CommCode.SYSCODE_MSG_TYPE_RECEIVE_CLIENT);
								      message.setSendid(userid);
								      message.setSendtype(CommCode.SYSCODE_MSG_TYPE_SEND_CLIENT);
								      message.setContent("赞了你的评论！");
								   //   message.setReserved12(portrait);
								      message.setEnabled(true);
								      message.setIsdeleted(false);
								      message.setCreateuser(-1);
								      message.setCreatedate(startDate);
								      message.setReserved1(actid);
								      message.setReserved2(acttype);
								      message.setReserved7(false);
								      message.setType(CommCode.SYSCODE_MSG_TYPE_PUSH);
								      mstMessageService.insert(message);
								      message.setReserved12(name);
								      JPushMessage.pushMessage(message, JPushEnum.ALL_ALIAS);
								}
							}
						}
					      
					} else {
						if (cnlist.get(0).getIsdeleted()) {

							cn = new ClientNum();
							cn.setId(cnlist.get(0).getId());
							cn.setUpdatedate(startDate);
							cn.setUpdateuser(userid);
							cn.setEnabled(true);
							cn.setIsdeleted(false);

							clientNumService.updateByPrimaryKeySelective(cn);

							resPara.setCode(CommCode.M_Y000000);
							resPara.setMessage(CommCode.M_D000001);
						} else {

							cn = new ClientNum();
							cn.setId(cnlist.get(0).getId());
							cn.setUpdatedate(startDate);
							cn.setUpdateuser(userid);
							cn.setEnabled(false);
							cn.setIsdeleted(true);

							clientNumService.updateByPrimaryKeySelective(cn);

							resPara.setCode(CommCode.M_Y000000);
							resPara.setMessage(CommCode.M_D000002);
						}
					}

				} else if (CommCode.SYSTEM_COUNT_FAVORITE.equals(numtype)) {// 收藏37

					if (null == cnlist || cnlist.size() == 0) {

						cn = new ClientNum();
						cn.setActid(actid);
						cn.setActtype(acttype);
						cn.setClientid(userid);
						cn.setCreatedate(startDate);
						cn.setCreateuser(userid);
						cn.setEnabled(true);
						cn.setIsdeleted(false);
						cn.setNum(1);
						cn.setNumtype(numtype);
						cn.setUpdatedate(startDate);						

						clientNumService.insert(cn);

						resPara.setCode(CommCode.M_Y000000);
						resPara.setMessage(CommCode.M_D000003);
					} else {
						if (cnlist.get(0).getIsdeleted()) {
							cn = new ClientNum();
							cn.setId(cnlist.get(0).getId());
							cn.setUpdatedate(startDate);
							cn.setUpdateuser(userid);
							cn.setEnabled(true);
							cn.setIsdeleted(false);

							clientNumService.updateByPrimaryKeySelective(cn);

							resPara.setCode(CommCode.M_Y000000);
							resPara.setMessage(CommCode.M_D000003);
						} else {
							cn = new ClientNum();
							cn.setId(cnlist.get(0).getId());
							cn.setUpdatedate(startDate);
							cn.setUpdateuser(userid);
							cn.setEnabled(false);
							cn.setIsdeleted(true);

							clientNumService.updateByPrimaryKeySelective(cn);

							resPara.setCode(CommCode.M_Y000000);
							resPara.setMessage(CommCode.M_D000004);
						}
					}

				} else if (CommCode.SYSTEM_COUNT_BROWSE.equals(numtype)) {// 浏览量

					if (StringUtils.isEmpty(userid)) {

						ClientNum clientnum = null;
						for (ClientNum clientNum : cnlist) {
							if (StringUtils.isEmpty(clientNum.getClientid())) {
								clientnum = clientNum;
							}
						}
						if (clientnum == null) {
							cn = new ClientNum();
							cn.setActid(actid);
							cn.setActtype(acttype);
							cn.setCreatedate(startDate);
							cn.setEnabled(true);
							cn.setIsdeleted(false);
							cn.setNum(1);
							cn.setNumtype(numtype);

							clientNumService.insert(cn);
						} else {
							cn = new ClientNum();

							Integer num = clientnum.getNum();

							Integer totlenum = num + 1;
							cn.setId(clientnum.getId());
							cn.setNum(totlenum);
							cn.setUpdatedate(startDate);

							clientNumService.updateByPrimaryKeySelective(cn);
						}

						resPara.setCode(CommCode.M_Y000000);
						resPara.setMessage(CommCode.M_Y000001);
					} else {
						if (null == cnlist || cnlist.size() == 0) {
							cn = new ClientNum();
							cn.setActid(actid);
							cn.setActtype(acttype);
							cn.setClientid(userid);
							cn.setCreatedate(startDate);
							cn.setCreateuser(userid);
							cn.setEnabled(true);
							cn.setIsdeleted(false);
							cn.setNum(1);
							cn.setNumtype(numtype);

							clientNumService.insert(cn);
						} else {
							cn = new ClientNum();

							Integer num = cnlist.get(0).getNum();

							Integer totlenum = num + 1;
							cn.setId(cnlist.get(0).getId());
							cn.setNum(totlenum);
							cn.setUpdatedate(startDate);
							cn.setUpdateuser(userid);
							cn.setNumtype(numtype);
							cn.setActid(actid);
							cn.setActtype(acttype);
							cn.setClientid(userid);

							clientNumService.updateByPrimaryKeySelective(cn);
						}

						resPara.setCode(CommCode.M_Y000000);
						resPara.setMessage(CommCode.M_Y000001);
						//addClientGrowth(cn);
					}

				} else {// 分享

					cn = new ClientNum();
					cn.setActid(actid);
					cn.setActtype(acttype);
					cn.setClientid(userid);
					cn.setCreatedate(startDate);
					cn.setCreateuser(userid);
					cn.setEnabled(true);
					cn.setIsdeleted(false);
					cn.setNum(1);
					cn.setNumtype(numtype);					

					clientNumService.insert(cn);

					resPara.setCode(CommCode.M_Y000000);
					resPara.setMessage(CommCode.M_Y000001);
					//addClientGrowth(cn);

				}
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
					.excludeFieldsWithoutExposeAnnotation().serializeNulls()
					.create();
			String jsonResult = gson.toJson(resPara);
	//		logger.info(jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

	//		logger.info("doPost end run(s): "+ DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	/**
	 * 
	 * @Title: addClientGrowth
	 * @Description: 浏览和分享增加功力值
	 * @param @param cn 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public void addClientGrowth(ClientNum cn) {
		Integer actid = cn.getActid();
		Integer acttype = cn.getActtype();
		Integer clientid = cn.getClientid();
		Integer numtype = cn.getNumtype();
		Integer growthType = 0;
		if (numtype.equals(CommCode.SYSTEM_COUNT_BROWSE)) {// 浏览
			if (acttype.equals(CommCode.SYSTEM_CARESEL_RANGE_WENW)) {// 文章
				growthType = CommCode.SYSTEM_GROWTH_RANGE_READ_ARTICLE;
			} else if (acttype.equals(CommCode.SYSTEM_CARESEL_RANGE_VIDEO)) {// 视频
				growthType = CommCode.SYSTEM_GROWTH_RANGE_VIEW_VIEDO;
			}
		} else if (numtype.equals(CommCode.SYSTEM_COUNT_SHARE)) {// 分享
			if (acttype.equals(CommCode.SYSTEM_CARESEL_RANGE_WENW)) {// 文章
				growthType = CommCode.SYSTEM_GROWTH_RANGE_SHARE_ARTICLE;
			} else if (acttype.equals(CommCode.SYSTEM_CARESEL_RANGE_VIDEO)) {// 视频
				growthType = CommCode.SYSTEM_GROWTH_RANGE_SHARE_VIEDO;
			} else if (acttype.equals(CommCode.SYSTEM_CARESEL_RANGE_PRO)) {// 活动
				growthType = CommCode.SYSTEM_GROWTH_RANGE_SHARE_ACTY;
			} else if (acttype.equals(CommCode.SYSTEM_CARESEL_RANGE_COURSE)) {// 课程
				growthType = CommCode.SYSTEM_GROWTH_RANGE_SHARE_COURSE;
			} else if (acttype.equals(CommCode.SYSTEM_CARESEL_RANGE_ONLINE)) {// 在线课程
				growthType = CommCode.SYSTEM_GROWTH_RANGE_SHARE_TRAIN;
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("clientid", clientid);
		map.put("growthid", actid);
		map.put("growthtype", growthType);

		List<ClientGrowth> list = clientGrowthService.queryByList(map,
				new PageBounds());
		// 当用户的此条数据没有记录时添加
		if (list == null || list.isEmpty()) {
			if (growthType != 0) {
				MstCode code = mstCodeMapper.selectByPrimaryKey(growthType);

				ClientGrowth cg = new ClientGrowth();
				cg.setClientid(clientid);
				cg.setGrowthid(actid);
				cg.setGrowthtype(growthType);
				cg.setGrowthvalue(Integer.parseInt(code.getCode()));
				cg.setEnabled(true);
				cg.setIsdeleted(false);
				cg.setCreatedate(new Date());
				cg.setCreateuser(clientid);

				clientGrowthService.insert(cg);

				// 查询用户成就表里
				List<ClientAccomplish> calist = clientAccomplishMapper
						.queryByUser(clientid);

				if (calist != null && !calist.isEmpty()) {
					// 当前达到的功力等级
					ClientAccomplish ca = calist.get(0);
					BigDecimal newGrowth = ca.getGrowthvalue().add(
							new BigDecimal(code.getCode()));
					// 查询功力值等级
					Map<String, Object> graMap = new HashMap<String, Object>();

					graMap.put("enabled", true);
					graMap.put("isDeleted", false);
					graMap.put("orderByClause", "mg.gravalue asc");

					List<MstGrade> mglist = mstGradeService.queryByList(graMap,
							new PageBounds());

					for (int i = 0; i < mglist.size(); i++) {
						MstGrade mstGrade = mglist.get(i);
						MstGrade nextGrade = null;
						if (i == mglist.size() - 1) {
							nextGrade = mstGrade;
						} else {
							nextGrade = mglist.get(i + 1);
						}
						// 如果等于当前等级
						if (mstGrade.getGravalue() == ca.getGrade()) {

							// 如果增加后的功力值大于下一等级,增加数据
							if (newGrowth.compareTo(new BigDecimal(nextGrade
									.getGrovalue())) >= 0) {
								// 更新功力值为当前最大值
								ca.setGrowthvalue(new BigDecimal(nextGrade
										.getGrovalue()));
								clientAccomplishMapper
								.updateByPrimaryKeySelective(ca);
								// 插入新的成就数据时
								ClientAccomplish c = new ClientAccomplish();
								c.setClientid(clientid);
								c.setGrade(mglist.get(i + 1).getGravalue());
								c.setGrowthvalue(newGrowth);
								c.setViewtime(ca.getViewtime());
								c.setCalorie(ca.getCalorie());
								c.setEnabled(true);
								c.setIsdeleted(false);
								c.setCreatedate(new Date());

								clientAccomplishMapper.insert(c);
							} else {
								ca.setGrowthvalue(newGrowth);
								clientAccomplishMapper
								.updateByPrimaryKeySelective(ca);
							}
						}
					}
				} else {
					// 插入新的成就数据时
					ClientAccomplish c = new ClientAccomplish();
					c.setClientid(clientid);
					c.setGrade(1);
					c.setGrowthvalue(new BigDecimal(code.getCode()));
					c.setEnabled(true);
					c.setIsdeleted(false);
					c.setCreatedate(new Date());

					clientAccomplishMapper.insert(c);
				}
			}
		}

	}

	@Override
	public CliNumReqPara getReqPara(HttpServletRequest request) {

		CliNumReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request,
					new CliNumReqPara());

			reqPara = (CliNumReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String actid = request.getParameter("actid");
			String acttype = request.getParameter("acttype");
			String numtype = request.getParameter("numtype");
			String receiveId = request.getParameter("receiveId");

//			logger.info("reqPara userid: " + userid);
//			logger.info("reqPara actid: " + actid);
//			logger.info("reqPara acttype: " + acttype);
//			logger.info("reqPara numtype: " + numtype);
//			logger.info("reqPara receiveId: " + receiveId);

			reqPara.setUserid(userid);
			reqPara.setActid(actid);
			reqPara.setActtype(acttype);
			reqPara.setNumtype(numtype);
			reqPara.setReceiveId(receiveId);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		CliNumReqPara nuReqPara = (CliNumReqPara) reqPara;
		BaseResponse nuResPara = (BaseResponse) resPara;

		if (StringUtils.isEmpty(nuReqPara.getActid())) {
			nuResPara.setCode(CommCode.M_A000000);
			nuResPara.setMessage(CommCode.M_E000002);
		} else if (StringUtils.isEmpty(nuReqPara.getActtype())) {
			nuResPara.setCode(CommCode.M_A000000);
			nuResPara.setMessage(CommCode.M_E000003);
		} else if (StringUtils.isEmpty(nuReqPara.getNumtype())) {
			nuResPara.setCode(CommCode.M_A000000);
			nuResPara.setMessage(CommCode.M_O000005);
		} else {
			flag = true;
		}

		return flag;
	}
}
